package com.tomorrowbbs.controller;

import com.tomorrowbbs.annotation.GlobalInterceptor;
import com.tomorrowbbs.annotation.VerifyParam;
import com.tomorrowbbs.controller.base.ABaseController;
import com.tomorrowbbs.domain.constants.Constants;
import com.tomorrowbbs.domain.dto.CreateImageCode;
import com.tomorrowbbs.domain.dto.SessionWebUserDto;
import com.tomorrowbbs.domain.dto.SysSetting4CommentDto;
import com.tomorrowbbs.domain.dto.SysSettingDto;
import com.tomorrowbbs.domain.enums.ResponseCodeEnum;
import com.tomorrowbbs.domain.enums.VerifyRegexEnum;
import com.tomorrowbbs.domain.vo.ResponseVo;
import com.tomorrowbbs.exception.BusinessException;
import com.tomorrowbbs.service.impl.EmailCodeServiceImpl;
import com.tomorrowbbs.service.impl.UserInfoServiceImpl;
import com.tomorrowbbs.utils.StringTools;
import com.tomorrowbbs.utils.SysCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.tomorrowbbs.utils.JsonUtils.logger;

@RestController
public class AccountController extends ABaseController {

    @Autowired
    private EmailCodeServiceImpl emailCodeService;
    @Autowired
    private UserInfoServiceImpl userInfoService;

    /**
     * 验证码
     */
    @RequestMapping("/checkCode")
    public void checkCode(HttpServletResponse response, HttpSession session, Integer type) throws IOException {
        CreateImageCode vCode = new CreateImageCode(130, 38, 5, 10);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String Code = vCode.getCode();
        //登录注册
        if (type == null || type == 0) {
            session.setAttribute(Constants.CHECK_CODE_KEY, Code);
        } else {
            //获取邮箱
            session.setAttribute(Constants.CHECK_CODE_KEY_EMAIL, Code);
        }
        vCode.write(response.getOutputStream());
    }

    /**
     * 发送验证码
     */
    @RequestMapping("/sendEmailCode")
    @GlobalInterceptor(checkParams = true)
    public ResponseVo sendEmailCode(HttpSession session, @VerifyParam(required = true) String email,
                                    @VerifyParam(required = true) String checkCode,
                                    @VerifyParam(required = true) Integer type) {

        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY_EMAIL))) {
                throw new BusinessException("图片验证码错误 邮箱");
            }
            emailCodeService.sendEmailCode(email, type);
            return getSuccessResponseVo(null);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY_EMAIL);
        }

    }

    /**
     * 注册
     */
    @RequestMapping("/register")
    @GlobalInterceptor(checkParams = true)
    public ResponseVo register(HttpSession session,
                               @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
                               @VerifyParam(required = true) String emailCode,
                               @VerifyParam(required = true, max = 20) String nickName,
                               @VerifyParam(required = true, min = 8, max = 18, regex = VerifyRegexEnum.PASSWORD) String password,
                               @VerifyParam(required = true) String checkCode) {

        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码错误 注册");
            }

            userInfoService.register(email, emailCode, nickName, password);
            return getSuccessResponseVo(null);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }

    /**
     * 登录
     */
    @RequestMapping("/login")
    @GlobalInterceptor(checkParams = true)
    public ResponseVo login(HttpSession session,
                            HttpServletRequest request,
                            @VerifyParam(required = true) String email,
                            @VerifyParam(required = true) String password,
                            @VerifyParam(required = true) String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码错误 注册");
            }
            SessionWebUserDto sessionWebUserDto = userInfoService.login(email, password, request.getRemoteAddr());
            session.setAttribute(Constants.SESSION_KEY, sessionWebUserDto);
            return getSuccessResponseVo(sessionWebUserDto);
        }finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }

    /**
     * 返回登录用户信息
     */
    @RequestMapping("/getUserInfo")
    public ResponseVo getUserInfo(HttpSession session){
        return getSuccessResponseVo(getUserInfoFromSession(session));
    }
    /**
     * 退出登录
     */
//    @RequestMapping("/loginOut")
//    public ResponseVo loginOut(HttpSession session){
//        session.invalidate();
//        return getSuccessResponseVo(null);
//    }
    @RequestMapping("/loginOut")
    public ResponseVo loginOut(HttpServletRequest request,
                               HttpServletResponse response,
                               HttpSession session) {

            // 1. 使 session 失效
            session.invalidate();

            // 2. 清除前端可能保存的用户令牌 Cookie（如果有）
            clearCookie(request, response, "userToken");

            // 3. 清除 JSESSIONID Cookie
            clearCookie(request, response, "JSESSIONID");

            return getSuccessResponseVo("登出成功");

    }

    // 辅助方法：清除指定名称的 Cookie
    private void clearCookie(HttpServletRequest request,
                             HttpServletResponse response,
                             String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    cookie.setValue("");
                    cookie.setPath("/"); // 设置路径，与登录时一致
                    cookie.setMaxAge(0); // 立即过期
                    cookie.setHttpOnly(true); // 如果原 Cookie 是 HttpOnly 的
                    response.addCookie(cookie);
                    break;
                }
            }
        }
    }

    /**
     * 获取系统设置
     */
    @RequestMapping("/getSysSetting")
    public ResponseVo getSysSetting(){
        SysSettingDto settingDto = SysCacheUtils.getSysSetting();
        SysSetting4CommentDto commentDto = settingDto.getCommentSetting();
        Map<String ,Object> result = new HashMap<>();
        result.put("commentOpen",commentDto.getCommentOpen());
        return getSuccessResponseVo(result);
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetPwd")
    @GlobalInterceptor(checkParams = true)
    public ResponseVo resetPwd(HttpSession session,
                               @VerifyParam(required = true) String email,
                               @VerifyParam(required = true, min = 8, max = 18, regex = VerifyRegexEnum.PASSWORD) String password,
                               @VerifyParam(required = true) String emailCode,
                               @VerifyParam(required = true) String checkCode){
        try{

            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码错误 注册");
            }
            userInfoService.resetPwd(email,password,emailCode);
            return getSuccessResponseVo(null);
        }finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }

}













